package org.zoomdev.zoom.rpc.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.zoomdev.zoom.rpc.MethodId;

import java.util.List;

public class ClientHandler extends ChannelInboundHandlerAdapter {

    private final Log log = LogFactory.getLog(ClientHandler.class);

    private ClientConnection connection;

    private final RpcClientListener listener;

    public ClientHandler(RpcClientListener listener) {
        this.listener = listener;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("rpc客户端连接成功");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof Command) {
            Command command = (Command) msg;
            Completer completer = connection.getCompleter(command.id);
            if (completer == null) {
                return;
            }
            completer.handler.setResult(command.func, command.bytes, completer);
        } else if (msg instanceof List) {
            connection.setMethodIds((List<MethodId>) msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.info("rpc客户端发生异常", cause);
        if (listener != null) {
            listener.onRpcException(cause);
        }
        ctx.close();
    }


    public ClientConnection getConnection() {
        return connection;
    }

    public void setConnection(ClientConnection connection) {
        this.connection = connection;
    }
}
